/**
 * User: alesj
 * Date: 18.3.2006
 * Time: 15:40:53
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blade.login;

import org.jboss.logging.Logger;
import org.jboss.seam.annotations.Around;
import org.jboss.seam.annotations.Within;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.contexts.Lifecycle;
import org.jboss.seam.interceptors.*;

import javax.ejb.AroundInvoke;
import javax.ejb.InvocationContext;
import javax.faces.event.PhaseId;
import java.lang.reflect.Method;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
@Around({BijectionInterceptor.class, ValidationInterceptor.class,
        ConversationInterceptor.class, BusinessProcessInterceptor.class})
@Within(RemoveInterceptor.class)
public class LoggedInInterceptor {
    private static final Logger log = Logger.getLogger(LoggedInInterceptor.class);

    @AroundInvoke
    public Object checkLoggedIn(InvocationContext invocation) throws Exception {

        boolean isLoggedIn = Contexts.getSessionContext().get(LoginIfInterceptor.LOGIN_KEY) != null;
        if (Lifecycle.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
            if (isLoggedIn) {
                log.info("User is already logged in");
                return invocation.proceed();
            } else {
                log.info("User is not logged in");
                return "login";
            }
        } else {
            if (isLoggedIn) {
                return invocation.proceed();
            } else {
                Method method = invocation.getMethod();
                if (method.getReturnType().equals(void.class)) {
                    return null;
                } else {
                    return method.invoke(invocation.getBean(), invocation.getParameters());
                }
            }
        }
    }

}
